package com.ssy.aop;

import com.ssy.entity.OperateLog;
import com.ssy.mapper.OperateLogMapper;
import com.ssy.utils.CurrentHolder;
import com.ssy.utils.JwtUtils;
import io.jsonwebtoken.Claims;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import java.time.LocalDateTime;
import java.util.Arrays;

/**
 * 操作日志切面类
 * 拦截标记了@OperateLog注解的方法，记录操作日志
 */
@Slf4j
@Component
@Aspect
public class OperateLogAspect {

    @Autowired
    private OperateLogMapper operateLogMapper;

    /**
     * 环绕通知
     * 拦截标记了@OperateLog注解的方法
     *
     * @param joinPoint 连接点
     * @return 方法执行结果
     * @throws Throwable 异常
     */
    @Around("@annotation(com.ssy.anno.Log)")
    public Object recordLog(ProceedingJoinPoint joinPoint) throws Throwable {
        // 记录开始时间
        long beginTime = System.currentTimeMillis();

        // 获取操作人ID
        Integer operateEmpId = getOperateEmpId();

        // 获取目标类名
        String className = joinPoint.getTarget().getClass().getName();

        // 获取目标方法名
        String methodName = joinPoint.getSignature().getName();

        // 获取方法参数
        Object[] args = joinPoint.getArgs();
        String methodParams = Arrays.toString(args);

        Object result = null;
        Exception exception = null;

        try {
            // 执行目标方法
            result = joinPoint.proceed();
            return result;
        } catch (Exception e) {
            exception = e;
            throw e;
        } finally {
            // 记录结束时间
            long endTime = System.currentTimeMillis();
            // 计算执行耗时
            long costTime = endTime - beginTime;

            // 获取返回值
            String returnValue = "";
            if (result != null) {
                returnValue = result.toString();
            }

            // 如果方法执行异常，记录异常信息
            if (exception != null) {
                returnValue = "异常信息：" + exception.getMessage();
            }

            // 创建操作日志对象
            OperateLog logEntity = new OperateLog();
            logEntity.setOperateEmpId(operateEmpId);
            logEntity.setOperateTime(LocalDateTime.now());
            logEntity.setClassName(className);
            logEntity.setMethodName(methodName);
            logEntity.setMethodParams(methodParams);
            logEntity.setReturnValue(returnValue);
            logEntity.setCostTime(costTime);

            // 保存操作日志
            log.info("记录操作日志： {}", logEntity);

            operateLogMapper.insert(logEntity);

            log.info("操作日志已记录: 类名={}, 方法名={}, 耗时={}ms", className, methodName, costTime);
        }
    }

    /**
     * 获取操作人ID
     * 从JWT令牌中解析用户ID
     *
     * @return 操作人ID
     */
    private Integer getOperateEmpId() {
        return CurrentHolder.getCurrentId(); // 如果获取失败，返回null
    }
}